package com.lcache.worker.service.handler;


import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: LIM
 * @description: 消息分发
 * @author: Alex Wu
 * @createDate: 2025-04-16 11:55
 **/
@Slf4j
public class MessageDispatcher {

    private static final Map<String, Channel> userChannelMap = new ConcurrentHashMap<>();
    private static final Map<Channel, String> channelUsers = new ConcurrentHashMap<>();

    public static void register(String userId, Channel channel) {
        userChannelMap.put(userId, channel);
        channelUsers.put(channel, userId);
        log.info("用户 {} 注册连接", userId);
    }

    public static void unregister(Channel channel) {
        String userId = channelUsers.remove(channel);
        if (userId != null) {
            userChannelMap.remove(userId);
            log.info("用户 {} 断开连接", userId);
        }
    }

    public static boolean isUserOnline(String userId) {
        return userChannelMap.containsKey(userId);
    }

    public static void sendToUser(String userId, String response) {
        Channel channel = userChannelMap.get(userId);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(new TextWebSocketFrame(response.toString()));
            log.info("向用户 {} 发送消息：{}", userId, response);
        } else {
            log.info("用户 {} 不在线，保存离线消息, 或者后续处理缓存", userId);
        }
    }


    public static void dispatchToAllUser(String message) throws ClientException {
        userChannelMap.forEach((userId, channel) -> {
            sendToUser(userId, message);
        });
    }


}
